package com.zzz.gp.utils;

import com.zzz.gp.bean.MailBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;


@Component
@Slf4j
public class MailService {
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送普通文本邮件
     *
     * @name: sendTextMail
     * @return: void
     * @auther: ZZZ
     * @date: 2021/9/6 15:29
     */
    @Async
    public void sendTextMail(MailBean mailBean) {
        MimeMessage mimeMailMessage = null;
        try {
            mimeMailMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //发送人
            mimeMessageHelper.setFrom(mailBean.getFrom());
            //接收人
            mimeMessageHelper.setTo(mailBean.getTo());
            //抄送
            if (mailBean.getCc() != null && mailBean.getCc().length > 0) {
                mimeMessageHelper.setCc(mailBean.getCc());
            }
            //主题
            mimeMessageHelper.setSubject(mailBean.getSubject());
            //内容
            mimeMessageHelper.setText(mailBean.getContent(), true);
            javaMailSender.send(mimeMailMessage);
            log.info("===邮件发送成功===");
        } catch (Exception e) {
            log.error("邮件发送失败:{}", e.getMessage());
        }
    }
}


